<template>
  <div class="skill_group_monitor" :style="screenHeight">
    <Spin size="large" fix v-if="spinShow"><Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon><div>正在加载中...</div></Spin>
    <div class="demo-split">
        <div class="demo-split-pane" style="float:left;border-right:1px solid #eeeeee;width:30%">
          <div class="ztree" id="seatTree"></div>
        </div>
        <div class="demo-split-pane" style="float:right;width:70%">
          <div  style="width: 100%;height: 40%;"></div>
          <div class="fixed_table" style="height: 60%">
            <div style="display:flex;width:80%">
              <Select v-model="agentStatus" filterable clearable placeholder="请选择员工状态进行查询"  @on-change="searchAgentStatus" title="员工状态查询" style="float: left;margin-right:10%">
                <Option v-for="item in agentStatusList" :value="item.name" :key="item.name">{{ item.name }}</Option>
              </Select>
              <Select v-model="autoRefreshTime" @on-change="autoRefreshMonitor" title="自动刷新时间">
                <Option v-for="item in autoRefreshList" :value="item.time" :key="item.time">{{ item.name }}</Option>
              </Select>
              <span style="color: red;font-size:20px;margin-left:10px" title="刷新倒计时">{{countdownTime}}</span>
            </div>
            <div style="height: 44px;">
              <Button type="primary" ghost :disabled="force_offline" @click="operateMonitor('force_offline')">强制下线</Button>
              <Button type="primary" ghost :disabled="force_busy" @click="operateMonitor('force_busy')">强制置忙</Button>
              <Button type="primary" ghost :disabled="force_idle" @click="operateMonitor('force_idle')">强制置闲</Button>
              <Button type="primary" ghost :disabled="force_hangup" @click="operateMonitor('force_hangup')">强 拆</Button>
              <Button type="primary" ghost :disabled="bargein" @click="operateMonitor('bargein')">强 插</Button>
              <Button type="primary" ghost :disabled="whisper" @click="operateMonitor('whisper')">密 语</Button>
              <Button type="primary" ghost :disabled="eavesdrop"  @click="operateMonitor('eavesdrop')">监 听</Button>
            </div>
            <div>
              <el-table highlight-current-row :data="infoTableList" @current-change="setSelected">
                <el-table-column
                  prop="status"
                  label="状态">
                </el-table-column>
                <el-table-column
                  prop="agentNum"
                  label="员工工号">
                </el-table-column>
                <el-table-column
                  prop="employeeName"
                  label="员工姓名">
                </el-table-column>
                <el-table-column
                  prop="time"
                  label="时长">
                  <template slot-scope="scope">
                    <span>{{ scope.row.time ? scope.row.time+'秒' : '' }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="deptName"
                  label="部门">
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "SeatMonitor",
    mixins:[],
    props:{
      pageCode:String
    },
    data(){
      return {
        autoRefreshTime:'0',
        autoRefreshList:[{time: '0', name: '停止自动刷新'},{time: '5', name: '5秒自动刷新'},{time: '10', name: '10秒自动刷新'},{time: '15', name: '15秒自动刷新'},{time: '20', name: '20秒自动刷新'},{time: '25', name: '25秒自动刷新'},{time: '30', name: '30秒自动刷新'}],
        countdownTime:0,
        showPageCount:0,
        force_offline:true,
        force_busy:true,
        force_idle:true,
        force_hangup:true,
        bargein:true,
        whisper:true,
        eavesdrop:true,
        split: 0.3,
        split1: 0.5,
        spinShow:false,
        queueNumber:'',
        Interval:'',
        inspectTreeData:[{"id":0,"pId":0,"name":"部门","open":true,"isParent":true,"busid":"-1"},{"id":-1,"pId":-1,"name":"技能组","open":true,"isParent":true,"busid":"-1"}],
        fatherId:0,
        tableHeight:{height:''},
        deptList:'',
        skillList:'',
        screenHeight:{height:''},
        agentStatus:'',
        agentStatusList:[{'id': '-1', 'name': '离线'},{'id': '0', 'name': '空闲'},{'id': '1', 'name': '振铃'},{'id': '2', 'name': '通话'},{'id': '3', 'name': '保持'},{'id': '4', 'name': '后处理'},{'id': '5', 'name': '被占用'},{'id': '6', 'name': '忙碌'},{'id': '7', 'name': '离开'},{'id': '8', 'name': '仅呼出'}],
        infoTableList:[],
        allTableList:[],
        currentBusid:'',
        timeMount:'',
        selectedNum:'',
        deptNameList:[],
        deptListInit:[],
        queueListInit:[]
      }
    },
    methods:{
      getTime:function(){
        clearInterval(this.timeMount);
        for (let k=0;k<this.allTableList.length;k++){
          let status=this.allTableList[k].status;
          if(status!="离线"){
            this.allTableList[k].time = this.allTableList[k].time+1;
          }
        }
        this.timeMount= setInterval(() =>{
          this.getTime();
        },1000);
      },
      setSelected:function(currentRow,index){
        if(currentRow == '00'){
          return;
        }
        let id = currentRow.id;
        let agentNum = currentRow.agentNum;
        let status = currentRow.status;
        if(id!="00"){
          this.selectedNum=agentNum;
        }
        this.force_offline=true;
        this.force_busy=true;
        this.force_idle=true;
        this.force_hangup=true;
        this.bargein=true;
        this.whisper=true;
        this.eavesdrop=true;
        if(status=="空闲"){
          this.force_offline=false;
          this.force_busy=false;
        }
        if(status=="通话"){
          this.eavesdrop=false;
          this.whisper=false;
          this.bargein=false;
          this.force_hangup=false;
          this.force_idle=true;
        }
        if(status=="忙碌"){
          this.force_idle=false;
          this.force_offline=false;
        }
        if(status=="仅呼出" || status=="后处理" || status=="仅呼出" || status=="离开"){
          this.force_idle=false;
        }
      },
      operateMonitor:function(eventMethod){
        window.opener.sendMessage(eventMethod,this.selectedNum);
      },
      autoRefresh:function(){
        let that=this;
        if(!this.currentBusid){
          // this.autoRefreshTime="0";
          this.$Message.info("请选择左侧目录中要刷新的技能组或部门的数据");
          return false;
        }
        
        window.opener.sendMessage('get_agents_monitor_info',this.currentBusid)
      },
      searchAgentStatus:function(){
        if(!this.agentStatus){
          this.infoTableList=this.allTableList;
          return false;
        }
        this.infoTableList=[];
        for (let i=0;i<this.allTableList.length;i++){
          if(this.agentStatus==this.allTableList[i].status){
            this.infoTableList.push(this.allTableList[i]);
          }
        }
      },
      initSearch:function (event) {
        let infoTableList=[];
        let allTableList=[];
        if(!event){
          return false;
        }
        let agentNames = event.agentname.split(",");
        let agentNums = event.agentnum.split(",");
        let agentGroupNums = event.agentgroupnum.split(",");
        let agentStatus = event.agentStatusName.split(",");
        let statusChangeTime = event.statuschangetime.split(",");
        if(agentStatus.length > 0){
          let sortData = this.sortStatus(agentNames,agentNums,agentGroupNums,agentStatus,statusChangeTime);
          agentNames = sortData[0]; //座席名称
          agentNums = sortData[1]; //座席号码
          agentGroupNums = sortData[2]; //座席组id
          agentStatus = sortData[3]; //座席状态
          statusChangeTime = sortData[4]; //座席时长
          for (let i=0;i<agentNums.length;i++){
            let status = agentStatus[i];
            let deptName="未知";
            if(this.deptNameList){
              for (let n=0;n<this.deptNameList.length;n++){
                if(this.deptNameList[n].id==agentGroupNums[i]){
                  deptName=this.deptNameList[n].name;
                }
              }
            }
            let time=parseInt(statusChangeTime[i])+1;
            if(status=="离线"){
              time="";
            }
            let param={
              id:"data"+i,
              status:status,
              statusId:agentStatus[i],
              agentNum:agentNums[i],
              employeeName:agentNames[i],
              time:time,
              deptName:deptName,
            };
            if(agentNums[i]!= event.agentno){
              if(!this.agentStatus){
                infoTableList.push(param);
                allTableList.push(param);
              }else {
                if(this.agentStatus==agentStatus[i]){
                  infoTableList.push(param);
                }
                allTableList.push(param);
              }
            }
          }
          for (let m=0;m<allTableList.length;m++){
            let status=allTableList[m].status;
            let agentNum=allTableList[m].agentNum;
            for (let n=0;n<this.allTableList.length;n++){
              let oldNum=this.allTableList[n].agentNum;
              let oldStatus=this.allTableList[n].status;
              if(agentNum==oldNum && status==oldStatus){
                if(infoTableList[m]){
                  infoTableList[m].time= this.allTableList[n].time;
                }
                if(allTableList[m]){
                  allTableList[m].time= this.allTableList[n].time;
                }
              }
            }
          }
          this.infoTableList=infoTableList;
          this.allTableList=allTableList;
        }
        if(infoTableList.length==0){
          let statusSet= new Map();
          this.initEChart(statusSet);
          this.infoTableList=[];
          return false;
        }
        let statusSet = this.stateSum(agentStatus);
        let isAll0 = true;
        for (let key of statusSet.keys()) {  
          if('空闲' != key){
            isAll0 = false;
          }
        }
        if(isAll0){
          return false;
        }
        let that=this;
        let count=0;
        for (let m=0;m<allTableList.length;m++) {
          let status = allTableList[m].status;
          let id = allTableList[m].id;
          let agentNum = allTableList[m].agentNum;
          if (this.selectedNum && agentNum == this.selectedNum) {
            setTimeout(function () {
              that.setSelected(id,agentNum,status);
            },1000);
            count++;
          }
        }
        if(count==0){
          this.setSelected("00","00","-1");
        }
      },
      sortStatus:function(agentNames,agentNums,agentGroupNums,agentStatus,statusChangeTime){
        let status =['2','0','6','-1',''];  //排列顺序：通话，空闲，忙碌，离线，其他
        let agentNames2 =[];
        let agentNums2 =[];
        let agentGroupNums2 = [];
        let agentStatus2 =[];
        let statusChangeTime2 =[];
        for(let n =0,len = status.length ;n < len; n++){
          let type = status[n];
          for(let m = 0,len = agentStatus.length; m < len; m++){
            let stat = agentStatus[m];
            if(this.loginName!=agentNums[m]){
              if(type === stat){
                agentNames2.push(agentNames[m]);
                agentNums2.push(agentNums[m]);
                agentGroupNums2.push(agentGroupNums[m]);
                agentStatus2.push(stat);
                statusChangeTime2.push(statusChangeTime[m]);
              }else if(n === 4 && stat != '2' && stat != '0' && stat != '6' && stat != '-1'){
                agentNames2.push(agentNames[m]);
                agentNums2.push(agentNums[m]);
                agentGroupNums2.push(agentGroupNums[m]);
                agentStatus2.push(stat);
                statusChangeTime2.push(statusChangeTime[m]);
              }
            }
          }
        }
        return [agentNames2,agentNums2,agentGroupNums2,agentStatus2,statusChangeTime2];
      },
      //计算座席状态个数
      stateSum:function(agentStatus){
        let stateNum = new Map();
        // 初始化stateNum
        agentStatus.forEach(item =>{
          stateNum.set(item,0);
        });

        // 统计数量
        agentStatus.forEach(item =>{
          stateNum.set(item,(stateNum.get(item)+1));
        });
        return stateNum;
      },
      //设备树初始化
      initSeatGroupTree:function (deptList,queueList) {
        let allNums = "";
      
        for (let i=0;i<deptList.length;i++){
          let name=deptList[i].name;
          let num=deptList[i].value;
          let pid=deptList[i].pid;
          let ID = deptList[i].id;
          let treeStr={
            id:ID,
            pId:pid,
            name:name,
            open:false,
            isParent:false,
            busid:num
          };
          this.inspectTreeData.push(treeStr);
          allNums += (num+",");
        }
        for (let i=0;i<queueList.length;i++){
          let name=queueList[i].name;
          let num=queueList[i].value;
          let treeStr={
            id:-2,
            pId:-1,
            name:name,
            open:false,
            isParent:false,
            busid:num
          };
          this.inspectTreeData.push(treeStr);
          allNums += (num+",");
        }
        this.currentBusid = allNums.substring(0,allNums.lastIndexOf(','));
        let that=this;
        let setting = {
          view: {
            dblClickExpand: false,
            showLine: true,
            selectedMulti: false
          },
          data: {
            simpleData: {
              enable:true,
              idKey: "id",
              pIdKey: "pId",
              rootPId: ""
            }
          },
          callback: {
            onClick: zTreeOnClick
          }
        };
        function zTreeOnClick(event,treeId,treeNode) {
          if(treeNode.busid!=-1){
            if(!treeNode.busid){
              that.$Message.info("该监控下,没有数据");
              let statusSet= new Map();
              that.infoTableList=[];
              that.allTableList=[];
              return false;
            }
            that.currentBusid=treeNode.busid;
            window.opener.sendMessage('get_agents_monitor_info',treeNode.busid)
            clearInterval(that.timeMount);
            that.getTime();
          }else{
            // 点击部门和技能组查询对应的全部
            let list = [];
            if(treeNode.name === '部门'){
              list = that.deptListInit;
            }else if(treeNode.name === '技能组'){
              list = that.queueListInit;
            }else{
              return ;
            }
            let nums = "";
            for (let i=0;i<list.length;i++){
              nums += (list[i].value+",");
            }
            that.currentBusid = nums.substring(0,nums.lastIndexOf(','));
            window.opener.sendMessage('get_agents_monitor_info',that.currentBusid)
          }
        }
        let zNodes =this.inspectTreeData;
        if (zNodes){
          $(document).ready(function(){
            $.fn.zTree.init($("#seatTree"), setting, zNodes);//t:用于展现 zTree 的 DOM 容器,setting:zTree 的配置数据,zNodes:zTree 的节点数据
          });
        }
      },
      monitorSeatData:function (event) {
        let retCode=event.retCode;
        if(retCode!='0'){
          this.$Message.info(event.reason);
          return false;
        }
        let eventMethod=event.method;
        if(eventMethod=="get_agents_monitor_info"){//获取技能组监控信息
          this.initSearch(event);
        }
      },
      //切换刷新时间
      autoRefreshMonitor:function(){
        let val=this.autoRefreshTime;
        this.historyRefreshTime=this.autoRefreshTime;
        let that=this;
        let reg=/^[0-9]*$/;
        if(val=='0'){
          clearInterval(this.Interval);
          this.countdownTime="0";
          return false;
        }
        clearInterval(this.Interval);
        if(reg.test(val)){
          val=parseInt(val);
          this.countdownTime=parseInt(val);
          this.Interval= setInterval(() =>{
            that.initCountdown();
          },1000);
        }
      },
      initCountdown:function () {
        this.countdownTime=this.countdownTime-1;
        if(this.countdownTime==0){
          this.countdownTime=parseInt(this.autoRefreshTime);
          this.autoRefresh();
          return false;
        }
      },
      rowClassName:function(row, index){
        if(this.infoTableList.length <= 0){
          return '';
        }else{
          if(row.agentNum == this.selectedNum){
            return 'rowClassName';
          }
        }
      }
    },
    mounted(){
      this.force_offline=true;
      this.force_busy=true;
      this.force_idle=true;
      this.force_hangup=true;
      this.bargein=true;
      this.whisper=true;
      this.eavesdrop=true;
      // this.screenHeight.height=this.mountHeight(92);
      // let clientHeight=(document.documentElement.clientHeight-92)*0.6-130;
      // this.tableHeight.height=clientHeight+'px';

      if(localStorage.getItem('skillGroup')){
        this.initSeatGroupTree(JSON.parse(localStorage.getItem('deptList')),JSON.parse(localStorage.getItem('skillGroup')));
      }
      if(localStorage.getItem('deptNameList')){
        this.deptNameList = JSON.parse(localStorage.getItem('deptNameList'));
      }
      // that.initSeatGroupTree(deptList,queueList);
      if(localStorage.getItem('customBusyStatusList')){
        let customBusyStatusList = JSON.parse(localStorage.getItem('customBusyStatusList'));
        if(customBusyStatusList){
          customBusyStatusList.forEach(item =>{
            this.agentStatusList.push({'id':item.value,'name':item.label})
          }) 
        }
      }
      window.monitorSeatData = this.monitorSeatData;
      window.document.title = "座席监控";
    },
    destroyed(){
      clearInterval(this.Interval);
      clearInterval(this.timeMount);
      this.autoRefreshTime="0";
      this.autoRefreshMonitor();
    },
    watch:{
    }
  }
</script>

<style scoped>
  .demo-split{
    height: 100%;
    border: 1px solid #dcdee2;
  }
  .demo-split-pane{
    height: 100%;
    padding: 10px;
  }
  .rowClassName{
    background-color:#57a3f3;
    td {
      background-color:#57a3f3;
    }
  }
</style>
